package com.mypopsy.widget;

import com.mypopsy.widget.pojo.MenuItem;
import com.mypopsy.widget.suggestions.SearchSuggestionsAdapter;
import com.mypopsy.widget.utils.AttrSetUtils;
import com.mypopsy.widget.utils.ViewUtils;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.components.*;
import ohos.agp.components.element.Element;
import ohos.app.Context;
import ohos.multimodalinput.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * A search UI widget that implements a floating search box also called persistent
 * search.
 */
public class FloatingSearchView extends DirectionalLayout {
    private static ListContainer listContainer;

    private static Image mNavButtonView;
    private static Image micMenu;
    private static Image menuImage;
    private static Image clearView;
    private static DependentLayout right_layout;
    private static StackLayout clearLayout;
    protected List<MenuItem> menus = new ArrayList<>();
    protected List<MenuItem> types = new ArrayList<>();
    private boolean isBack = false;
    private boolean isCloseSearchInput = true;
    private boolean isRightDown = false;
    private Element currentElement;
    private Element backElement;
    private boolean leftIconShown = true;

    private static OnSuggestionClickListener onSuggestionClickListener;
    private OnSearchFocusChangedListener mFocusListener;
    private OnIconClickListener mNavigationClickListener;
    private onSearchInputClickListener mSearchInputClickListener;
    private OnMenuItemClickListener mOnMenuItemClickListener;
    private OnMenuMicrophoneClickListener mOnMenuMicrophoneClickListener;

    private static List<String> suggestionsList = new ArrayList<>();

    private static String searchedItem = "";

    private String floatingSearchHint;

    private static int floatingSearchBarMarginLeft = 0;

    private static int floatingSearchBarMarginTop = 0;

    private static int floatingSearchBarMarginRight = 0;

    private static int suggestion;

    private DirectionalLayout dlSuggestion;

    private DirectionalLayout search_query_section;

    private LogoTextField mSearchInput;

    public FloatingSearchView(Context context) {
        this(context, null);
    }

    /**
     * SearchResultsListAdapter Constructor
     *
     * @param context context of ability
     * @param attrSet for attribute set
     */
    public FloatingSearchView(Context context, AttrSet attrSet) {
        this(context, attrSet, null);
    }

    public FloatingSearchView(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
        initComponent(attrSet);
    }

    public FloatingSearchView(Context context, AttrSet attrSet, String styleName, List<String> suggestions) {
        this(context, attrSet, styleName);
        FloatingSearchView.suggestionsList = suggestions;
    }

    private void initComponent(AttrSet attrSet) {
        Component rootView = LayoutScatter.getInstance(getContext())
                .parse(ResourceTable.Layout_floating_search_layout, null, false);
        Component mSearchInputComp = rootView.findComponentById(ResourceTable.Id_search_bar_text);
        if (mSearchInputComp instanceof TextField) {
            mSearchInput = (LogoTextField) mSearchInputComp;
        }
        Component listContainerComp = rootView.findComponentById(ResourceTable.Id_suggestions_list);
        if (listContainerComp instanceof ListContainer) {
            listContainer = (ListContainer) listContainerComp;
        }
        Component ivBackComp = rootView.findComponentById(ResourceTable.Id_iv_back);
        if (ivBackComp instanceof Image) {
            mNavButtonView = (Image) ivBackComp;
        }
        Component dlSuggestionComp = rootView.findComponentById(ResourceTable.Id_dl_suggestion);
        if (dlSuggestionComp instanceof DirectionalLayout) {
            dlSuggestion = (DirectionalLayout) dlSuggestionComp;
        }
        Component search_query_sectionComp =
                rootView.findComponentById(ResourceTable.Id_search_query_section);
        if (search_query_sectionComp instanceof DirectionalLayout) {
            search_query_section = (DirectionalLayout) search_query_sectionComp;
        }

        micMenu = (Image) rootView.findComponentById(ResourceTable.Id_micImage);
        menuImage = (Image) rootView.findComponentById(ResourceTable.Id_menu);
        right_layout = (DependentLayout) rootView.findComponentById(ResourceTable.Id_ly_right);
        clearView = (Image) rootView.findComponentById(ResourceTable.Id_clearView);
        clearLayout = (StackLayout) rootView.findComponentById(ResourceTable.Id_clearLayout);

        if (attrSet != null) {
            applyXmlAttributes(attrSet);
        }
        setClick();
        addComponent(rootView);
    }

    private void setClick() {
        mNavButtonView.setClickedListener(new ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (mNavigationClickListener != null) {
                    mNavigationClickListener.onNavigationClick();
                }
            }
        });
        mSearchInput.setClickedListener(new ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (mSearchInputClickListener != null) {
                    mSearchInputClickListener.onSearchInputClick();
                }
            }
        });

        mSearchInput.setKeyEventListener(new KeyEventListener() {
            @Override
            public boolean onKeyEvent(Component component, KeyEvent keyEvent) {
                if (keyEvent.getKeyCode() != KeyEvent.KEY_ENTER) {
                    return false;
                }
                mNavigationClickListener.onNavigationClick();
                return true;
            }
        });
        menuImage.setClickedListener(new ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (mOnMenuItemClickListener != null) {
                    mOnMenuItemClickListener.onMenuItemClick(getContext(), menuImage);
                }
            }
        });
        clearView.setClickedListener(new ClickedListener() {
            @Override
            public void onClick(Component component) {
                mSearchInput.setText("");
                mSearchInput.setHint(floatingSearchHint);
                clearLayout.setVisibility(INVISIBLE);
            }
        });
        micMenu.setClickedListener(new ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (mOnMenuMicrophoneClickListener != null) {
                    mOnMenuMicrophoneClickListener.onMenuMicrophoneClick();
                }
            }
        });
        setFocusChangedListenerForSearchInput();
        addTextObserverForSearchInput();
    }

    private void applyXmlAttributes(AttrSet attrSet) {
        if (attrSet != null) {
            floatingSearchHint = AttrSetUtils.optString(attrSet,
                    "fsv_searchHint", floatingSearchHint);
            mSearchInput.setLogo(AttrSetUtils.optElement(attrSet, "logo", null));
            setContentBackgroundColor(
                    AttrSetUtils.optColor(attrSet, "fsv_contentBackgroundColor", 0));
            setIcon(AttrSetUtils.optElement(attrSet, "fsv_icon", null));
            micMenu.setImageElement(AttrSetUtils.optElement(attrSet, "fsv_microphone", null));
            clearView.setImageElement(AttrSetUtils.optElement(attrSet, "fsv_clear", null));
            menuImage.setImageElement(AttrSetUtils.optElement(attrSet, "fsv_menu", null));
            backElement = AttrSetUtils.optElement(attrSet, "fsv_back", null);
        }

        ComponentContainer.LayoutConfig config = createLayoutConfig(attrSet);
        //  dlSuggestion.setLayoutConfig(config);
        search_query_section.setLayoutConfig(config);

    }

    public void setContentBackgroundColor(int color) {

    }

    public void setHint(String hint) {
        mSearchInput.setHint(hint);
    }

    public void setIcon(Element element) {
        currentElement = element;
        showIcon(element != null);
        mNavButtonView.setMarginLeft(20);
        mNavButtonView.setMarginRight(20);
        mNavButtonView.setComponentSize(64, 64);
        mNavButtonView.setImageElement(element);
    }

    public void showLogo(boolean show) {
        mSearchInput.showLogo(show);
        mSearchInput.invalidate();
    }

    public void showIcon(boolean show) {
        leftIconShown = show;
        mNavButtonView.setVisibility(show ? Component.VISIBLE : Component.INVISIBLE);
        mSearchInput.setTranslationX(show ? 0 : -mNavButtonView.getWidth());
    }

    private void setFocusChangedListenerForSearchInput() {
        ArrayList<String> tempArrayList = new ArrayList<String>();
        if (mSearchInput.getText().length() != 0) {
            int textlength = mSearchInput.getText().length();
            for (String currentItem : suggestionsList) {
                if (textlength <= suggestionsList.size()) {
                    if (currentItem.toLowerCase(Locale.getDefault())
                            .contains(mSearchInput.getText().toLowerCase(Locale.getDefault()))) {
                        tempArrayList.add(currentItem);
                    }
                }
            }
        } else {
            tempArrayList = (ArrayList<String>) getSuggestions(suggestion);
        }

        ArrayList<String> finalTempArrayList = tempArrayList;
        mSearchInput.setFocusChangedListener(new FocusChangedListener() {
            @Override
            public void onFocusChange(Component component, boolean focus) {
                if (focus) {
                    SearchSuggestionsAdapter listItemProvider =
                            new SearchSuggestionsAdapter(getContext(),
                            finalTempArrayList,
                            new SearchSuggestionsAdapter.OnItemClicklistener() {
                                @Override
                                public void onItemClick(String selectedItem, boolean isRight) {
                                    listContainer.setVisibility(HIDE);
                                    onSuggestionClickListener.onSuggestionClick(selectedItem);
                                    mSearchInput.setText(selectedItem);
                                    mSearchInput.clearFocus();
                                    if (mSearchInput.getText().length() == 0) {
                                        mSearchInput.showLogo(true);
                                    }
                                    mSearchInput.setHint("");
                                    mSearchInput.invalidate();
                                    mNavButtonView.setImageElement(currentElement);
                                    clearLayout.setVisibility(INVISIBLE);
                                    fadeIn(isBack);
                                    isBack = false;
                                    isCloseSearchInput = true;
                                }
                            });
                    listContainer.setItemProvider(listItemProvider);
                }
            }
        });
    }

    private void addTextObserverForSearchInput() {
        ArrayList<String> tempArrayList = new ArrayList<String>();
        mSearchInput.addTextObserver(new Text.TextObserver() {
            @Override
            public void onTextUpdated(String inputText, int start, int before, int count) {
                tempArrayList.clear();
                if (inputText.length() > 0) {
                    int textlength = inputText.length();
                    for (String currentItem : suggestionsList) {
                        if (textlength <= suggestionsList.size()) {
                            if (currentItem.toLowerCase(Locale.getDefault())
                                    .contains(inputText.toLowerCase(Locale.getDefault()))) {
                                tempArrayList.add(currentItem);
                            }
                        }
                    }
                    clearLayout.setVisibility(VISIBLE);
                    SearchSuggestionsAdapter searchSuggestionsAdapter =
                            new SearchSuggestionsAdapter(getContext(),
                            tempArrayList, new SearchSuggestionsAdapter.OnItemClicklistener() {
                        @Override
                        public void onItemClick(String selectedItem, boolean isRight) {
                            if (onSuggestionClickListener != null) {
                                if (!isRight) {
                                    listContainer.setVisibility(HIDE);
                                    onSuggestionClickListener.onSuggestionClick(selectedItem);
                                    mSearchInput.setText(selectedItem);
                                    mSearchInput.clearFocus();
                                    if (mSearchInput.getText().length() == 0) {
                                        mSearchInput.showLogo(true);
                                    }
                                    mSearchInput.setHint("");
                                    mSearchInput.invalidate();
                                    mNavButtonView.setImageElement(currentElement);
                                    clearLayout.setVisibility(INVISIBLE);
                                    fadeIn(isBack);
                                    isBack = false;
                                    isCloseSearchInput = true;
                                } else {
                                    isRightDown = isRight;
                                    mSearchInput.setText(selectedItem);
                                    clearLayout.setVisibility(VISIBLE);
                                }
                            }
                        }
                    });

                    listContainer.setItemProvider(searchSuggestionsAdapter);
                } else {
                    tempArrayList.clear();
                    clearLayout.setVisibility(INVISIBLE);
                    SearchSuggestionsAdapter searchSuggestionsAdapter = new SearchSuggestionsAdapter(getContext(),
                            tempArrayList, null);
                    listContainer.setItemProvider(searchSuggestionsAdapter);
                }
            }
        });
    }

    private void handleZeroTextInput() {
        SearchSuggestionsAdapter listItemProvider = new SearchSuggestionsAdapter(getContext(),
                getSuggestions(suggestion),
                new SearchSuggestionsAdapter.OnItemClicklistener() {
                    @Override
                    public void onItemClick(String selectedItem, boolean isRight) {
                        onSuggestionClickListener.onSuggestionClick(selectedItem);
                        mNavButtonView.setImageElement(currentElement);
                        mNavButtonView.setVisibility(VISIBLE);
                        clearLayout.setVisibility(INVISIBLE);
                        right_layout.setVisibility(VISIBLE);
                        mSearchInput.setText(selectedItem);
                        listContainer.setVisibility(HIDE);
                        mSearchInput.clearFocus();
                    }
                });
        listContainer.setItemProvider(listItemProvider);
    }

    private ComponentContainer.LayoutConfig createLayoutConfig(AttrSet attrSet) {
        ComponentContainer.LayoutConfig config = new ComponentContainer.LayoutConfig(
                ComponentContainer.LayoutConfig.MATCH_PARENT,
                ComponentContainer.LayoutConfig.MATCH_CONTENT);
        config.setMarginLeft(AttrSetUtils.optInt(attrSet, "fsv_searchBarMarginLeft", 5));
        config.setMarginTop(AttrSetUtils.optInt(attrSet, "fsv_searchBarMarginTop", 5));
        config.setMarginRight(AttrSetUtils.optInt(attrSet, "fsv_searchBarMarginRight", 5));
        return config;
    }

    /**
     * method for initialization
     *
     * @param onSuggestionClickListener for attribute set
     * @param count                     for suggestion list count
     */

    public static void init(int count, List<String> suggestions,
                            OnSuggestionClickListener onSuggestionClickListener) {
        FloatingSearchView.onSuggestionClickListener = onSuggestionClickListener;
        FloatingSearchView.suggestion = count;
        FloatingSearchView.suggestionsList = suggestions;
    }

    /**
     * Interface for suggestion click
     */
    public interface OnSuggestionClickListener {
        /**
         * Called when the alert is set to be dismissed with an animation.
         *
         * @param alert the alert
         */
        void onSuggestionClick(String alert);
    }

    /**
     * method for getsuggestions
     *
     * @param count for number of suggestions
     * @return string list
     */
    private static List<String> getSuggestions(int count) {
        List<String> suggestionList = new ArrayList<>();
        String colorSuggestion;
        for (String currentItem : suggestionsList) {
            colorSuggestion = currentItem;
            suggestionList.add(colorSuggestion);
            if (suggestionList.size() == count) {
                break;
            }
        }
        return suggestionList;
    }

    public CharSequence getText() {
        return mSearchInput.getText();
    }

    public void setText(String text) {
        mSearchInput.setText(text);
    }

    public LogoTextField getSearchInput() {
        return mSearchInput;
    }

    public void setSearchInput(LogoTextField mSearchInput) {
        this.mSearchInput = mSearchInput;
    }

    public void changeNavButtonView() {
        if (isBack) {
            listContainer.setVisibility(HIDE);
            mSearchInput.setText(mSearchInput.getText());
            if (mSearchInput.getText().length() == 0) {
                mSearchInput.showLogo(true);
            }
            mSearchInput.setHint("");
            mSearchInput.invalidate();
            mNavButtonView.setImageElement(currentElement);
            fadeIn(isBack);
            isBack = false;
            mSearchInput.clearFocus();
            ViewUtils.hideKeyboard();
            clearLayout.setVisibility(INVISIBLE);
            isCloseSearchInput = true;
        } else {
            mNavButtonView.setImageElement(backElement);
            mSearchInput.requestFocus();
            mSearchInput.setHint(floatingSearchHint);
            mSearchInput.showLogo(false);
            if (mSearchInput.getText().length() != 0) {
                clearLayout.setVisibility(VISIBLE);
            } else {
                clearLayout.setVisibility(INVISIBLE);
            }
            mSearchInput.invalidate();
            listContainer.setVisibility(VISIBLE);
            ViewUtils.showKeyboard();
            fadeIn(isBack);
            isBack = true;
            isCloseSearchInput = false;
        }
        showIcon(leftIconShown);
    }

    public void changeSearchInputView() {
        if (!leftIconShown) {
            mNavButtonView.setVisibility(VISIBLE);
            mSearchInput.setTranslationX(0);
        }
        if (closeSearchInput()) {
            isCloseSearchInput = false;
            searchedItem = mSearchInput.getText();
            mNavButtonView.setImageElement(backElement);
            if (searchedItem.isEmpty()) {
                mSearchInput.setText("");
            }
            if (mSearchInput.getText().length() != 0) {
                clearLayout.setVisibility(VISIBLE);
            }
            listContainer.setVisibility(VISIBLE);
            fadeIn(isBack);
            mSearchInput.setHint(floatingSearchHint);
            mSearchInput.showLogo(false);
            mSearchInput.invalidate();
            isBack = true;
        }
    }

    private boolean closeSearchInput() {
        return isCloseSearchInput;
    }

    private void fadeIn(boolean enabled) {
        AnimatorProperty animatorProperty = new AnimatorProperty();
        animatorProperty.setTarget(right_layout)
                .alphaFrom(enabled ? 0 : 1f)
                .alpha(enabled ? 1f : 0)
                .setDuration(10)
                .start();
    }

    public interface OnSearchListener {
        void onSearchAction(CharSequence text);
    }

    public interface OnIconClickListener {
        void onNavigationClick();
    }

    public interface onSearchInputClickListener {
        void onSearchInputClick();
    }

    public interface OnMenuItemClickListener {
        void onMenuItemClick(Context context, Component component);
    }

    public interface OnMenuMicrophoneClickListener {
        void onMenuMicrophoneClick();
    }

    public interface OnSearchFocusChangedListener {
        void onFocusChanged(boolean focused);
    }

    public void setOnIconClickListener(OnIconClickListener navigationClickListener) {
        mNavigationClickListener = navigationClickListener;
    }

    public void setOnSearchInputClickListener(onSearchInputClickListener searchInputClickListener) {
        mSearchInputClickListener = searchInputClickListener;
    }

    public void setOnSearchFocusChangedListener(OnSearchFocusChangedListener focusListener) {
        mFocusListener = focusListener;
    }

    public void setOnMenuItemClickListener(OnMenuItemClickListener menuItemClickListener) {
        mOnMenuItemClickListener = menuItemClickListener;
    }

    public void setOnMenuMicrophoneClickListener(OnMenuMicrophoneClickListener microphoneClickListener) {
        mOnMenuMicrophoneClickListener = microphoneClickListener;
    }


    public void setOnSearchListener(final OnSearchListener listener) {
        mSearchInput.setKeyEventListener(new KeyEventListener() {
            @Override
            public boolean onKeyEvent(Component component, KeyEvent keyEvent) {
                if (keyEvent.getKeyCode() != KeyEvent.KEY_ENTER) {
                    return false;
                }
                listener.onSearchAction(mSearchInput.getText());
                return true;
            }
        });
    }
}